using System;
using System.ComponentModel;
using CommandLineMapper.Interfaces;

namespace CommandLineMapper {
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class CommandOptionAttribute : Attribute, ICommandOption {
        private readonly string[] _aliases;
        private readonly Type _optionType;
        private readonly TypeConverter _converter;

        public CommandOptionAttribute(Type optionType, string[] aliases) 
            : this(optionType, aliases, null) {}

        public CommandOptionAttribute(Type optionType, string[] aliases, TypeConverter converter)
        {
            if(optionType == null) {
                throw new ArgumentNullException("optionType");
            }
            if(aliases == null) {
                throw new ArgumentNullException("aliases");
            }
            if(aliases.Length == 0) {
                throw new ArgumentException("At least one alias must be specified for property");
            }
            
            _optionType = optionType;
            _aliases = aliases;
            _converter = converter ?? TryReceiveTypeConverter(optionType);
        }

        private static TypeConverter TryReceiveTypeConverter(Type optionType) {
            return TypeDescriptor.GetConverter(optionType);
        }

        #region Implementation of ICommandOption

        public Type OptionType {
            get { return _optionType; }
        }

        public string[] Aliases {
            get { return _aliases; }
        }

        public TypeConverter Converter {
            get { return _converter; }
        }

        #endregion
    }
}